#include <cstdio>


#include "ParticleSystem.h"

//------------------------------------------------------------------------------

ParticleSystem::ParticleSystem()
{
	timeStep = 0.015;
	gravitationalAcceleration = Vector3(0, -9.81, 0);
	numIterations = 3;
	dampingAir = 0;
	collisionSystem = 0;
}

//------------------------------------------------------------------------------

void ParticleSystem::update()
{
	//fprintf(stderr, "ParticleSystem::update()\n");
	accumulateForces();
	verlet();
	for(int i = 0; i < numIterations; ++i)
		satisfyConstraints();
}

//------------------------------------------------------------------------------

void ParticleSystem::addObject(Object* o)
{
	o->particleSystem = this;
	object.insert(o);
}

//------------------------------------------------------------------------------

void ParticleSystem::removeObject(Object* o)
{
	object.erase(o);
}

//------------------------------------------------------------------------------

void ParticleSystem::verlet()
{
	set<Object*>::iterator o;
	for(o = object.begin(); o != object.end(); ++o) {
		(*o)->verlet();
	}
}

//------------------------------------------------------------------------------

void ParticleSystem::satisfyConstraints()
{
	if(collisionSystem)
		collisionSystem->handleCollisions();
	set<Object*>::iterator o;
	for(o = object.begin(); o != object.end(); ++o) {
		(*o)->satisfyConstraints();
	}
}

//------------------------------------------------------------------------------

void ParticleSystem::accumulateForces()
{
	set<Object*>::iterator o;
	for(o = object.begin(); o != object.end(); ++o) {
		// reset all the forces to gravity only
		(*o)->setAcc(gravitationalAcceleration);
		// add aditional forces specific to each object
		(*o)->accumulateForces();
		// reset damping for all particles
		(*o)->setDamping(dampingAir);
	}
}
